package com.lkm.app_ui.ui;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.MBaseFragment;
import com.lkm.app_ui.Market2_0ConfigeImpl;
import com.lkm.app_ui.MyApplication;
import com.lkm.app_ui.R;
import com.lkm.app_ui.RouterUINavigation;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.help.AppHelp;
import com.lkm.app_ui.help.QRCodeUtil;
import com.lkm.comlib.Config;
import com.lkm.comlib.ui.BaseFragmentActivity;
import com.lkm.frame.module.event.ModuleInitEvent;
import com.lkm.frame.otto.LinkBusCycleWrapper;
import com.lkm.frame.otto.Observer;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.task2.CTaskExecutor;
import com.lkm.frame.task2.TaskAdapter;
import com.lkm.frame.util.CycleHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.javatool.lang.RunnablePR;
import com.lkm.market2_0.m.app_main.AppMainModule;
import com.lkm.market2_0.m.steelyardserver.OnSteelyardKeyEvent;
import com.lkm.market2_0.m.steelyardstatus.StatusInfo;
import com.lkm.market2_0.m.steelyardstatus.SteelyardStatusManagerModule;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;



public class DelegateInitFragment extends MBaseFragment {

    public static DelegateInitFragment initFragment;

    @Override
    protected int configLayoutResID() {
        return R.layout.fragment_init;
    }

    public static int STATE_NotMAC1 = 1;
    public static int STATE_HaveMAC_NotINFO2 = 2;
    public static int STATE_HaveMAC_HaveINFO3 = 3;
    public static int STATE_AppMainModuleFail4 = 4;








    private TextView tv_tips;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initFragment = this;

        CreateQR createQR = new CreateQR();
        createQR.action();
        createQR.execTask();

    }




    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (initFragment == this)
            initFragment = null;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tv_tips = findViewById(R.id.tv_tips);
        reState();

        ((TextView)findViewById(R.id.tv_version)).setText(AppHelp.getLocalVersionName());
        reOnKeyEvent();
    }

    public void reState() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                handlState();
            }
        });
    }

    private void handlState() {
        String steelyardMac = RunTimeData.LoaclSteelyardMac;//AppConst.getApplication().getSharedPreferences("settingapp", Context.MODE_PRIVATE).getString("steelyardMac", "");
        int state = 0;

        if (StringHelp.isEmpty(steelyardMac)) {
            state = STATE_NotMAC1;

            if(AppConst.getTaskManager2().getRunTask(Market2_0ConfigeImpl.getHoldSteelyardMacTaskId())!=null){
                tv_tips.setText("同步后台台秤唯一码到本地...");
            }else {
                tv_tips.setText("等待台秤...");
            }
        } else if (RunTimeData.steelyardInfo == null) {
            state = STATE_HaveMAC_NotINFO2;

            tv_tips.setText("获取台秤数据中..." + steelyardMac);
        }else
            if (AppConst.getModuleManager().peekModule(AppMainModule.class) == null) {
                state = STATE_AppMainModuleFail4;
                tv_tips.setText("加载初始化数据中，请保证网络通畅...");


        } else {
            state = STATE_HaveMAC_HaveINFO3;

            RouterUINavigation.getInstance().dismissAll();
            RouterUINavigation.getInstance().goSaleFragment((BaseFragmentActivity) getActivity());
        }



    }
    int keyEventCount = 0;
    private void reOnKeyEvent() {
        LinkBusCycleWrapper.register(new Observer<OnSteelyardKeyEvent>() {
            @Override
            public Class<OnSteelyardKeyEvent> getBusEventClass() {
                return OnSteelyardKeyEvent.class;
            }

            @Override
            public void onReceiver(OnSteelyardKeyEvent data, Runnable nextRun) {
                try {

                    if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_FUN) {
                        data.setIntercepted(true);

                        if (keyEventCount % 2 == 0)
                            RouterUINavigation.getInstance().showWifi((BaseFragmentActivity) getActivity(), true);
                        else
                            RouterUINavigation.getInstance().dismissAll();
                        keyEventCount++;
                    }
                } finally {
                    nextRun.run();
                }
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }
    @Override
    protected boolean configIsLockKey() {
        return true;
    }



    protected class CreateQR extends TaskAdapter<Object[], Void, Bitmap> {

        public CreateQR() {
            super(new CTaskExecutor<Object[], Void, Bitmap>(Config.getTaskExecutor(), Looper.getMainLooper()), InfoFragment.CreateQR.class.getName(), MyApplication.getInstance().getTaskManager2());
        }


        @Override
        public void doExecuting(Object[] param) {
            super.doExecuting(param);
            mTaskExecutor.executor(new RunnablePR<Object[], Void>() {
                @Override
                public Void run(Object[] objects) {
                    complete(onExecuting(objects));
                    return null;
                }
            }, param);
        }

        public Bitmap onExecuting(Object[] param) {

            while (AppConst.deviceUncode==null){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            String uid = AppConst.deviceUncode;

            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("uid", uid);
            String s = "";
            try{
                s = jsonObject.toString();
            }catch (Error e){}

            Bitmap bitmap = QRCodeUtil.createImage(s, 200, 200);
            return bitmap;
        }

        @Override
        public void onFinish(Bitmap bitmap) {
            super.onFinish(bitmap);
            if (isExit()) return;
            try {
                ImageView img_qr = (ImageView) findViewById(R.id.img_qr);
                img_qr.setImageBitmap(bitmap);
            }catch (Exception e){}

        }
    }
}
